<template>
  <div class="task-create">
    <el-card>
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="160px"
        style="max-width: 1000px; margin: 0 auto"
      >
        <el-form-item label="年级" prop="gradeLevel">
          <el-select v-model="form.gradeLevel" placeholder="请选择年级">
            <el-option
              v-for="(label, value) in levelMap"
              :key="value"
              :label="label"
              :value="Number(value)"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入任务标题" />
        </el-form-item>

        <!-- 添加试卷表格 -->
        <el-form-item label="试卷列表">
          <el-table :data="form.paperItems" style="width: 100%">
            <el-table-column label="学科" width="120">
              <template #default="{ row }">
                {{ getSubjectName(row.subjectId) }}
              </template>
            </el-table-column>
            <el-table-column prop="name" label="名称" min-width="200" />
            <el-table-column prop="createTime" label="创建时间" width="180" />
            <el-table-column label="操作" width="100">
              <template #default="{ row, $index }">
                <el-button type="danger" size="small" @click="handleRemovePaper($index)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" :loading="loading" @click="handleSubmit">提交</el-button>
          <el-button :disabled="loading" @click="handleReset">重置</el-button>
          <el-button type="success" @click="handleAddPaper">添加试卷</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 添加试卷对话框 -->
    <el-dialog v-model="paperDialogVisible" width="80%" title="选择试卷">
      <div class="search-controls">
        <span class="search-label">学科：</span>
        <el-select
          v-model="paperSearch.subjectId"
          placeholder="学科"
          style="width: 120px; margin-right: 10px"
          clearable
        >
          <el-option
            v-for="subject in subjectList"
            :key="subject.id"
            :label="`${subject.name} (${subject.levelName})`"
            :value="subject.id"
          />
        </el-select>
        <el-button type="primary" @click="handleSearchPapers">搜索</el-button>
      </div>

      <el-table :data="paperList" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="学科" width="120">
          <template #default="{ row }">
            {{ getSubjectName(row.subjectId) }}
          </template>
        </el-table-column>
        <el-table-column prop="name" label="名称" width="300" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
      </el-table>

      <el-pagination
        v-model:current-page="paperPagination.current"
        v-model:page-size="paperPagination.size"
        :total="paperPagination.total"
        :page-sizes="[5, 10, 20, 50]"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="paperDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirmAddPapers">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { useRoute, useRouter } from "vue-router";
import UserAPI from "@/api/system/user.api";
import { ElMessage } from "element-plus";

// 年级映射：1-6 小学，7-9 初中，10-12 高中
const levelMap: Record<number, string> = {
  1: "一年级",
  2: "二年级",
  3: "三年级",
  4: "四年级",
  5: "五年级",
  6: "六年级",
  7: "初一",
  8: "初二",
  9: "初三",
  10: "高一",
  11: "高二",
  12: "高三",
};

const route = useRoute();
const router = useRouter();
const formRef = ref();
const subjectList = ref<any[]>([]);
const loading = ref(false);
const isEdit = computed(() => !!route.query.id);

// 试卷对话框相关
const paperDialogVisible = ref(false);
const paperList = ref<any[]>([]);
const selectedPapers = ref<any[]>([]);
const paperSearch = reactive({
  subjectId: undefined as number | undefined,
  gradeLevel: undefined as number | undefined,
});
const paperPagination = reactive({
  current: 1,
  size: 5,
  total: 0,
});

const form = reactive({
  id: null as number | null,
  gradeLevel: undefined as number | undefined,
  title: "",
  paperItems: [] as any[],
});

const rules = {
  gradeLevel: [{ required: true, message: "请选择年级", trigger: "change" }],
  title: [{ required: true, message: "请输入任务标题", trigger: "blur" }],
};

// 获取学科列表
function getSubjectList() {
  UserAPI.getSubjectList()
    .then((data: any) => {
      subjectList.value = data || [];
    })
    .catch(() => {
      // ElMessage.error('获取学科列表失败');
    });
}

function getSubjectName(subjectId: number) {
  const subject = subjectList.value.find((s) => s.id === subjectId);
  return subject ? `${subject.name} (${subject.levelName})` : "未知学科";
}

// 获取任务详情
async function fetchDetail(id: number) {
  loading.value = true;
  try {
    const res: any = await UserAPI.getTaskDetail(id);
    const data = res;

    if (data) {
      form.id = data.id ?? id;
      form.gradeLevel = data.gradeLevel;
      form.title = data.title || "";
      form.paperItems = data.paperItems || [];
    }
  } catch {
    ElMessage.error("获取任务详情失败");
  } finally {
    loading.value = false;
  }
}

function handleSubmit() {
  formRef.value?.validate((valid: boolean) => {
    if (!valid) return;
    loading.value = true;

    const payload: any = {
      gradeLevel: form.gradeLevel,
      title: form.title,
      paperItems: form.paperItems,
    };

    // 如果是编辑，添加id
    if (isEdit.value && form.id) {
      payload.id = form.id;
    }

    UserAPI.editTask(payload)
      .then(() => {
        ElMessage.success(isEdit.value ? "编辑成功" : "创建成功");
        router.back();
      })
      .catch(() => {
        ElMessage.error(isEdit.value ? "编辑失败" : "创建失败");
      })
      .finally(() => {
        loading.value = false;
      });
  });
}

function handleReset() {
  if (isEdit.value && form.id) {
    fetchDetail(form.id);
  } else {
    Object.assign(form, {
      id: null,
      gradeLevel: undefined,
      title: "",
      paperItems: [],
    });
  }
}

function handleAddPaper() {
  paperDialogVisible.value = true;
  // 重置搜索条件
  Object.assign(paperSearch, {
    subjectId: undefined,
    gradeLevel: form.gradeLevel,
  });
  // 加载试卷列表
  getPaperList();
}

function getPaperList() {
  const payload: any = {
    pageIndex: paperPagination.current,
    pageSize: paperPagination.size,
    paperType: 6, // 只显示任务试卷类型
  };

  // 如果有搜索条件，添加到 payload 中
  if (paperSearch.subjectId) {
    payload.subjectId = paperSearch.subjectId;
  }
  if (paperSearch.gradeLevel) {
    payload.level = paperSearch.gradeLevel;
  }

  UserAPI.getTaskExamPage(payload)
    .then((res: any) => {
      paperList.value = res.list || [];
      paperPagination.total = res.total || 0;
    })
    .catch(() => {
      ElMessage.error("获取试卷列表失败");
      paperList.value = [];
      paperPagination.total = 0;
    });
}

function handleSearchPapers() {
  // 重置到第一页
  paperPagination.current = 1;
  getPaperList();
}

function handleSelectionChange(selection: any[]) {
  selectedPapers.value = selection;
}

function handleSizeChange(size: number) {
  paperPagination.size = size;
  paperPagination.current = 1; // 重置到第一页
  getPaperList();
}

function handleCurrentChange(current: number) {
  paperPagination.current = current;
  getPaperList();
}

function handleConfirmAddPapers() {
  // 将选中的试卷添加到任务中
  selectedPapers.value.forEach((paper) => {
    if (!form.paperItems.find((p) => p.id === paper.id)) {
      form.paperItems.push(paper);
    }
  });
  paperDialogVisible.value = false;
  selectedPapers.value = [];
}

function handleRemovePaper(index: number) {
  form.paperItems.splice(index, 1);
}

onMounted(() => {
  getSubjectList();

  const id = Number(route.query.id);
  if (id) {
    form.id = id;
    fetchDetail(id);
  }
});
</script>

<style scoped lang="scss">
.task-create {
  padding: 32px 0;
}

.search-controls {
  display: flex;
  align-items: center;
  margin-bottom: 20px;

  :deep(.el-input),
  :deep(.el-select),
  :deep(.el-button) {
    height: 32px;
  }
}

.search-label {
  margin-right: 8px;
  font-size: 14px;
  color: var(--el-text-color-regular);
  white-space: nowrap;
}

:deep(.el-dialog) {
  --el-dialog-padding-primary: 20px;
}
</style>
